﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Web.UI;

namespace XinYiOffice.Common
{
    /// <summary>
    /// Web工具类
    /// </summary>
    /// <returns>Web工具类</returns>
    public class WebHelper
    {
        /// <summary>
        /// 返回用户IP
        /// </summary>
        /// <returns>返回用户IP</returns>
        public static string GetIP()
        {
            string myip = "";

            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                myip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                myip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }//得到ip
            return myip;
        }




        /// <summary>
        /// 返回绝对路径
        /// </summary>
        /// <param name="MyPath">要转换的路径</param>
        /// <returns>返回绝对路径</returns>
        public static string Get_MyPath(string MyPath)
        {
            return System.Web.HttpContext.Current.Server.MapPath(MyPath);
        }
        /// <summary>
        /// 弹出窗口
        /// --window.open(page,url,widthx,heightX)
        /// </summary>
        /// <param name="mypage"></param>
        /// <param name="url"></param>
        /// <param name="widthX"></param>
        /// <param name="heightX"></param>
        /// <returns>弹出窗口</returns>
        public static void WindowOpen(System.Web.UI.Page mypage, string url, int widthX, int heightX)
        {
            string strscript = "<script language='javascript'>";
            strscript += "window.open('" + url + "','_blank','toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=no,top=50,left=200,width=" + widthX + ",height=" + heightX + "');";
            strscript += "</script>";
            if (!mypage.IsStartupScriptRegistered("ShowMsg"))
                mypage.RegisterStartupScript("window.open", strscript);

        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="mypage"></param>
        /// <returns>关闭窗口</returns>
        public static void WindowClose(System.Web.UI.Page mypage)
        {
            string strscript = "<script language='javascript'>";
            strscript += "window.close();";
            strscript += "</script>";
            if (!mypage.IsStartupScriptRegistered("ShowMsg"))
                mypage.RegisterStartupScript("window.close", strscript);
        }
        /// <summary>
        /// 在页面上弹出信息
        /// </summary>
        /// <param name="mypage"></param>
        /// <param name="info"></param>
        /// <returns>在页面上弹出信息</returns>
        public static void ShowMessage(System.Web.UI.Page mypage, string info)
        {
            info = info.Replace("\n", "");
            string strscript = "<script language='javascript'>";
            strscript += "alert('" + info + "');";
            strscript += "</script>";

            mypage.Response.Write(strscript);

            //if (!mypage.IsStartupScriptRegistered("ShowMsg"))
            //    mypage.RegisterStartupScript("ShowMsg", strscript);
        }
        /// <summary>
        /// 在页面上弹出信息、并转向到指定的URL
        /// </summary>
        /// <param name="mypage">该页面的实例</param>
        /// <param name="info">弹出的消息</param>
        /// <param name="Url">指定的URL</param>
        /// <returns>在页面上弹出信息、并转向到指定的URL</returns>
        public static void ShowMessage_Url(System.Web.UI.Page mypage, string info,string Url)
        {
            info = info.Replace("\n", "");
            string strscript = "<script language='javascript'>";
            strscript += "alert('" + info + "');";
            strscript += "window.location='" + Url + "';";
            strscript += "</script>";
            if (!mypage.IsStartupScriptRegistered("ShowMsg"))
                mypage.RegisterStartupScript("ShowMsg", strscript);
        }
        /// <summary>
        /// 在页面上弹出信息,并转向指定的URL重载打开
        /// </summary>
        /// <param name="mypage"></param>
        /// <param name="info"></param>
        /// <param name="Url"></param>
        public static void ShowMessage_Urln(System.Web.UI.Page mypage, string info, string Url)
        {
           
            info = info.Replace("\n", "");
            string strscript = "<script language='javascript'>";
            strscript += "alert('" + info + "');";
            strscript += "window.location='"+Url+"?s='+Math.random();";
            strscript += "</script>";

            mypage.Response.Write(strscript);
        }
        /// <summary>
        /// 在页面上弹出信息，并使控件获得焦点
        /// </summary>
        /// <param name="name">脚本块标识。</param>
        /// <param name="str_Message">提示信息</param>
        /// <param name="focusControl">需要获得焦点的控件名称</param>
        /// <returns>在页面上弹出信息，并使控件获得焦点</returns>
        public static void ShowMessage(string name, string str_Message, string focusControl)
        {
            ExecuteJS(name, string.Format("<script>alert('{0}');document.forms(0).{1}.focus(); document.forms(0).{2}.select();</script>", str_Message, focusControl, focusControl));
        }
        /// <summary>
        /// 在客户端注册Javascript脚本,以便调用
        /// </summary>
        /// <param name="name">脚本块标识。</param>
        /// <param name="content">脚本代码</param>
        /// <returns>在客户端注册Javascript脚本,以便调用</returns>
        public static void RegJS(string name, string content)
        {
            string js = content;
            if (js.IndexOf("<script") < 0)
            {
                js = "<script language='JavaScript'>" + js + "</script>";
            }
            Page page = (Page)HttpContext.Current.Handler;
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), name, js);
        }
        /// <summary>
        /// 在客户端执行一段脚本
        /// </summary>
        /// <param name="name">脚本块标识。</param>
        /// <param name="js">要执行的脚本</param>
        /// <returns>在客户端执行一段脚本</returns>
        public static void ExecuteJS(string name, string js)
        {
            if (js.IndexOf("<script") < 0)
            {
                js = string.Format("<script language='JavaScript'>{0}</script>", js);
            }
            Page page = (Page)HttpContext.Current.Handler;
            page.ClientScript.RegisterStartupScript(page.GetType(), name, js);
        }
        /// <summary>
        /// 回车转Tab键
        /// </summary>
        /// <returns>回车转Tab键</returns>
        public static void EnterToTab()
        {
            string EnterToTab = "<script language='javascript' event='onkeydown' for='document'> if(event.keyCode==13 && event.srcElement.type!='button' && event.srcElement.type!='submit' && event.srcElement.type!='reset' && event.srcElement.type!='textarea' && event.srcElement.type!='' && event.srcElement.type!='imagebutton')event.keyCode=9;</script>";
            RegJS("enterToTab", EnterToTab);
        }
        /// <summary>
        /// 弹出确认对话框
        /// </summary>
        /// <param name="name">脚本块标识.</param>
        /// <param name="strMessage">消息字符串</param>
        /// <returns>弹出确认对话框</returns>
        public static void Confirm(string name, string strMessage)
        {
            RegJS(name, "<script> confirm('" + strMessage + "')</script>");
        }
        /// <summary>
        /// 使控件获得焦点
        /// </summary>
        /// <param name="ctlId">获得焦点控件Id值,比如：txt_Name</param>
        /// <returns>使控件获得焦点</returns>
        public static void GetFocus(string ctlId)
        {
            ExecuteJS("GetFocus", string.Format("<script>document.getElementById('{0}').focus(); document.getElementById('{1}').select();</script>", ctlId, ctlId));
        }
        /// <summary>
        /// 关闭网页，生成关闭网页的脚本代码
        /// </summary>
        /// <returns>关闭网页的脚本代码</returns>
        public static void ClosePage()
        {
            StringBuilder js = new StringBuilder();
            js.Append("<script language='JavaScript'>window.close();</script>");
            RegJS("ClosePage", js.ToString());
        }
        /// <summary>
        /// 打印对话框
        /// </summary>
        /// <param name="mypage"></param>
        /// <returns>打印对话框</returns>
        public static void WindowPrint(System.Web.UI.Page mypage)
        {
            string strscript = "<script language='javascript'>";
            strscript += "window.print();";
            strscript += "</script>";
            if (!mypage.IsStartupScriptRegistered("WindowPrint"))
                mypage.RegisterStartupScript("window.print", strscript);

        }
        /// <summary>
        /// 转向Url
        /// </summary>
        /// <param name="mypage"></param>
        /// <param name="url"></param>
        /// <returns>转向Url</returns>
        public static void Redirect(System.Web.UI.Page mypage, string url)
        {
            string scr = "<script>window.location='" + url + "';</script>";

            mypage.Response.Write(scr);

            //string strscript = "<script language='javascript'>";
            //strscript += "window.location='" + url + "';";
            //strscript += "</script>";
            //if (!mypage.IsStartupScriptRegistered("Redirect"))
            //{ 
            //    mypage.RegisterStartupScript("Redirect", strscript);
            //}
        }
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
        /// <summary>
        /// 以指定的ContentType输出指定文件文件
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="filename">输出的文件名</param>
        /// <param name="filetype">将文件输出时设置的ContentType</param>
        /// <returns>以指定的ContentType输出指定文件文件</returns>
        public static void ResponseFile(string filepath, string filename, string filetype)
        {
            Stream iStream = null;

            // 缓冲区为10k
            byte[] buffer = new Byte[10000];

            // 文件长度
            int length;

            // 需要读的数据长度
            long dataToRead;

            try
            {
                // 打开文件
                iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);


                // 需要读的数据长度
                dataToRead = iStream.Length;

                HttpContext.Current.Response.ContentType = filetype;
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + UrlEncode(filename.Trim()).Replace("+", " "));

                while (dataToRead > 0)
                {
                    // 检查客户端是否还处于连接状态
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        length = iStream.Read(buffer, 0, 10000);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        // 如果不再连接则跳出死循环
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    // 关闭文件
                    iStream.Close();
                }
            }
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// 判断文件名是否为浏览器可以直接显示的图片文件名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否可以直接显示</returns>
        public static bool IsImgFilename(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
            {
                return false;
            }
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
        }
        /// <summary>
        /// 生成指定数量的html空格符号
        /// </summary>
        /// <returns>生成指定数量的html空格符号</returns>
        public static string Spaces(int nSpaces)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < nSpaces; i++)
            {
                sb.Append(" &nbsp;&nbsp;");
            }
            return sb.ToString();
        }
        /// <summary>
        /// 检测是否符合email格式
        /// </summary>
        /// <param name="strEmail">要判断的email字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsValidEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        /// <summary>
        /// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.*
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="iparray"></param>
        /// <returns></returns>
        public static bool InIPArray(string ip, string[] iparray)
        {

            string[] userip = SplitString(ip, @".");
            for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++)
            {
                string[] tmpip = SplitString(iparray[ipIndex], @".");
                int r = 0;
                for (int i = 0; i < tmpip.Length; i++)
                {
                    if (tmpip[i] == "*")
                    {
                        return true;
                    }

                    if (userip.Length > i)
                    {
                        if (tmpip[i] == userip[i])
                        {
                            r++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }

                }
                if (r == 4)
                {
                    return true;
                }


            }
            return false;

        }
        /// <summary>
        /// 根椐Email得到网址
        /// </summary>
        /// <param name="strEmail">Email地址</param>
        /// <returns>网址</returns>
        public static string GetEmailHostName(string strEmail)
        {
            if (strEmail.IndexOf("@") < 0)
            {
                return "";
            }
            return strEmail.Substring(strEmail.LastIndexOf("@")).ToLower();
        }
        /// <summary>
        /// 清理类似于www @ 之类的字符串
        /// </summary>
        public static string CleanInput(string strIn)
        {
            return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
        }
        /// <summary>
        /// 返回URL中结尾的文件名
        /// </summary>		
        public static string GetFilename(string url)
        {
            if (url == null)
            {
                return "";
            }
            string[] strs1 = url.Split(new char[] { '/' });
            return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
        }
        /// <summary>
        /// 替换回车换行符为html换行符
        /// </summary>
        public static string StrFormat(string str)
        {
            string str2;

            if (str == null)
            {
                str2 = "";
            }
            else
            {
                str = str.Replace("\r\n", "<br />");
                str = str.Replace("\n", "<br />");
                str2 = str;
            }
            return str2;
        }
        /// <summary>
        /// 转换为静态html
        /// </summary>
        public static void transHtml(string path, string outpath)
        {
            Page page = new Page();
            StringWriter writer = new StringWriter();
            page.Server.Execute(path, writer);
            FileStream fs;
            if (File.Exists(page.Server.MapPath("") + "\\" + outpath))
            {
                File.Delete(page.Server.MapPath("") + "\\" + outpath);
                fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
            }
            else
            {
                fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
            }
            byte[] bt = Encoding.Default.GetBytes(writer.ToString());
            fs.Write(bt, 0, bt.Length);
            fs.Close();
        }
        /// <summary>
        /// 替换html字符
        /// </summary>
        public static string EncodeHtml(string strHtml)
        {
            if (strHtml != "")
            {
                strHtml = strHtml.Replace(",", "&def");
                strHtml = strHtml.Replace("'", "&dot");
                strHtml = strHtml.Replace(";", "&dec");
                return strHtml;
            }
            return "";
        }
        /// <summary>
        /// 清理字符串中的HTML格式 
        /// </summary>
        /// <param name="strHtml">字符串</param>
        /// <returns>不带HTML的字符串</returns>
        public static string ClearHtml(string strHtml)
        {
            if (strHtml != "")
            {
                Regex r = null;
                Match m = null;

                r = new Regex(@"<\/?[^>]*>", RegexOptions.IgnoreCase);
                for (m = r.Match(strHtml); m.Success; m = m.NextMatch())
                {
                    strHtml = strHtml.Replace(m.Groups[0].ToString(), "");
                }
            }
            return strHtml;
        }
        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveHtml(string content)
        {
            string regexstr = @"<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            HttpContext.Current.Response.AppendCookie(cookie);

        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.AppendCookie(cookie);

        }
        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string strName)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
            {
                return HttpContext.Current.Request.Cookies[strName].Value.ToString();
            }

            return "";
        }
        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string str)
        {
            return HttpUtility.HtmlEncode(str);
        }
        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }
        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }
        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        public static string[] SplitString(string strContent, string strSplit)
        {
            if (strContent.IndexOf(strSplit) < 0)
            {
                string[] tmp = { strContent };
                return tmp;
            }
            return Regex.Split(strContent, @strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 进行指定的替换(脏字过滤)
        /// </summary>
        public static string StrFilter(string str, string bantext)
        {
            string text1 = "";
            string text2 = "";
            string[] textArray1 = SplitString(bantext, "\r\n");
            for (int num1 = 0; num1 < textArray1.Length; num1++)
            {
                text1 = textArray1[num1].Substring(0, textArray1[num1].IndexOf("="));
                text2 = textArray1[num1].Substring(textArray1[num1].IndexOf("=") + 1);
                str = str.Replace(text1, text2);
            }
            return str;
        }
        /// <summary>
        /// 获得伪静态页码显示链接
        /// </summary>
        /// <param name="curPage">当前页数</param>
        /// <param name="countPage">总页数</param>
        /// <param name="url">超级链接地址</param>
        /// <param name="extendPage">周边页码显示个数上限</param>
        /// <returns>页码html</returns>
        public static string GetStaticPageNumbers(int curPage, int countPage, string url, string expname, int extendPage)
        {
            int startPage = 1;
            int endPage = 1;

            string t1 = "<a href=\"" + url + "-1" + expname + "\">&laquo;</a>&nbsp;";
            string t2 = "<a href=\"" + url + "-" + countPage + expname + "\">&raquo;</a>&nbsp;";

            if (countPage < 1) countPage = 1;
            if (extendPage < 3) extendPage = 2;

            if (countPage > extendPage)
            {
                if (curPage - (extendPage / 2) > 0)
                {
                    if (curPage + (extendPage / 2) < countPage)
                    {
                        startPage = curPage - (extendPage / 2);
                        endPage = startPage + extendPage - 1;
                    }
                    else
                    {
                        endPage = countPage;
                        startPage = endPage - extendPage + 1;
                        t2 = "";
                    }
                }
                else
                {
                    endPage = extendPage;
                    t1 = "";
                }
            }
            else
            {
                startPage = 1;
                endPage = countPage;
                t1 = "";
                t2 = "";
            }

            StringBuilder s = new StringBuilder("");

            s.Append(t1);
            for (int i = startPage; i <= endPage; i++)
            {
                if (i == curPage)
                {
                    s.Append("&nbsp;");
                    s.Append(i);
                    s.Append("&nbsp;");
                }
                else
                {
                    s.Append("&nbsp;<a href=\"");
                    s.Append(url);
                    s.Append("-");
                    s.Append(i);
                    s.Append(expname);
                    s.Append("\">");
                    s.Append(i);
                    s.Append("</a>&nbsp;");
                }
            }
            s.Append(t2);

            return s.ToString();
        }
        /// <summary>
        /// 获得帖子的伪静态页码显示链接
        /// </summary>
        /// <param name="expname"></param>
        /// <param name="countPage">总页数</param>
        /// <param name="url">超级链接地址</param>
        /// <param name="extendPage">周边页码显示个数上限</param>
        /// <returns>页码html</returns>
        public static string GetPostPageNumbers(int countPage, string url, string expname, int extendPage)
        {
            int startPage = 1;
            int endPage = 1;
            int curPage = 1;

            string t1 = "<a href=\"" + url + "-1" + expname + "\">&laquo;</a>&nbsp;";
            string t2 = "<a href=\"" + url + "-" + countPage + expname + "\">&raquo;</a>&nbsp;";

            if (countPage < 1) countPage = 1;
            if (extendPage < 3) extendPage = 2;

            if (countPage > extendPage)
            {
                if (curPage - (extendPage / 2) > 0)
                {
                    if (curPage + (extendPage / 2) < countPage)
                    {
                        startPage = curPage - (extendPage / 2);
                        endPage = startPage + extendPage - 1;
                    }
                    else
                    {
                        endPage = countPage;
                        startPage = endPage - extendPage + 1;
                        t2 = "";
                    }
                }
                else
                {
                    endPage = extendPage;
                    t1 = "";
                }
            }
            else
            {
                startPage = 1;
                endPage = countPage;
                t1 = "";
                t2 = "";
            }

            StringBuilder s = new StringBuilder("");

            s.Append(t1);
            for (int i = startPage; i <= endPage; i++)
            {
                s.Append("&nbsp;<a href=\"");
                s.Append(url);
                s.Append("-");
                s.Append(i);
                s.Append(expname);
                s.Append("\">");
                s.Append(i);
                s.Append("</a>&nbsp;");
            }
            s.Append(t2);

            return s.ToString();
        }
        /// <summary>
        /// 获得页码显示链接
        /// </summary>
        /// <param name="curPage">当前页数</param>
        /// <param name="countPage">总页数</param>
        /// <param name="url">超级链接地址</param>
        /// <param name="extendPage">周边页码显示个数上限</param>
        /// <returns>页码html</returns>
        public static string GetPageNumbers(int curPage, int countPage, string url, int extendPage)
        {
            int startPage = 1;
            int endPage = 1;

            if (url.IndexOf("?") > 0)
            {
                url = url + "&";
            }
            else
            {
                url = url + "?";
            }

            string t1 = "<a href=\"" + url + "&page=1" + "\">&laquo;</a>&nbsp;";
            string t2 = "<a href=\"" + url + "&page=" + countPage + "\">&raquo;</a>&nbsp;";

            if (countPage < 1) countPage = 1;
            if (extendPage < 3) extendPage = 2;

            if (countPage > extendPage)
            {
                if (curPage - (extendPage / 2) > 0)
                {
                    if (curPage + (extendPage / 2) < countPage)
                    {
                        startPage = curPage - (extendPage / 2);
                        endPage = startPage + extendPage - 1;
                    }
                    else
                    {
                        endPage = countPage;
                        startPage = endPage - extendPage + 1;
                        t2 = "";
                    }
                }
                else
                {
                    endPage = extendPage;
                    t1 = "";
                }
            }
            else
            {
                startPage = 1;
                endPage = countPage;
                t1 = "";
                t2 = "";
            }

            StringBuilder s = new StringBuilder("");

            s.Append(t1);
            for (int i = startPage; i <= endPage; i++)
            {
                if (i == curPage)
                {
                    s.Append("&nbsp;");
                    s.Append(i);
                    s.Append("&nbsp;");
                }
                else
                {
                    s.Append("&nbsp;<a href=\"");
                    s.Append(url);
                    s.Append("page=");
                    s.Append(i);
                    s.Append("\">");
                    s.Append(i);
                    s.Append("</a>&nbsp;");
                }
            }
            s.Append(t2);

            return s.ToString();
        }

    }
}
